package com.tudouji.framework.task;

import com.tudouji.common.utils.DateUtils;
import com.tudouji.common.utils.StringUtils;
import com.tudouji.framework.task.MeituanDataProcessUtil.ProcessWrapper;
import com.tudouji.project.customer.service.ICustomerService;
import com.tudouji.project.mt.domain.*;
import com.tudouji.project.mt.service.*;
import com.tudouji.project.organization.domain.Department;
import com.tudouji.project.organization.domain.Organization;
import com.tudouji.project.organization.service.IOrganizationService;
import com.tudouji.project.organization.service.ISupplierService;
import com.tudouji.project.product.domain.Salesspecification;
import com.tudouji.project.product.service.ISalesspecificationService;
import com.tudouji.project.store.domain.Stockunit;
import com.tudouji.project.store.domain.Storehouseroom;
import com.tudouji.project.store.domain.Storeroom;
import com.tudouji.project.store.service.IStockunitService;
import com.tudouji.project.store.service.IStorehouseroomService;
import com.tudouji.project.store.service.IStoreroomService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.List;

/**
 * 美团门店销售订单数据加工
 */
@Service("mtsalesdp")
@Slf4j
public class MeituanSalesDataProcessing {
    @Autowired
    private IStoreroomService storeroomService;

    @Autowired
    private IStorehouseroomService storehouseroomService;

    @Autowired
    private IMtShopService mtShopService;

    @Autowired
    private MeituanDataProcessUtil meituanDataProcessUtil;

    @Autowired
    private IMtSalesService mtSalesService;

    @Autowired
    private IMtSalesItemsService mtSalesItemsService;

    @Autowired
    private IMtFoodconsumService mtFoodconsumService;

    @Autowired
    private IMtFoodcostcardService mtFoodcostcardService;

    @Autowired
    private IMtFoodcostcarditemService mtFoodcostcarditemService;

    private static int mtFoodERPShrType = 2;  //美团菜品对应的ERP库间类型 2-产品库
    private static int mtGoodsERPShrType = 1;  //美团原料对应的ERP库间类型 1-原料库

    /**
     * 处理美团入库单的数据加工
     */
    public void salesProcess(){
        log.info("=========美团门店销售订单数据加工开始===============");
        List<MtShop> mtShopList = mtShopService.selectMtShopList(new MtShop());
        for(MtShop mtShop:mtShopList){
            if(mtShop.getStatus()==1){
                salesProcessForShop(mtShop);
            }
        }
        log.info("=========美团门店销售订单数据加工结束===============");

    }

    /**
     * 处理某一店铺的菜品销售单
     * @param mtShop
     */
    public void salesProcessForShop(MtShop mtShop){
        MtSales lookup = new MtSales();
        //设置查询条件，查询状态为 1 - 初始，或者状态为 10 - 资料不全的美团入库单主表数据
        //需要有时间范围，仅查询推送数据前 n 天 到当前的数据即可
        //Long startBiztime = DateUtils.addDays(mtShop.getWhinAsyndate(),-3).getTime();
        lookup.setStartBiztime(mtShop.getPushdate().getTime());
        lookup.setMtShopid(mtShop.getId());
        //lookup.setStatus(1);
        List<MtSales> mtSalesList = mtSalesService.selectMtSalesList(lookup);
        for(MtSales mtSales:mtSalesList){
            if(mtSales.getStatus()!=null
                    && mtSales.getStatus()!=1 && mtSales.getStatus()!=10){
                continue;
            }
            mtSales.setRemark("");
            salesProcessForWhinOrder(mtSales,mtShop);
            //更新主表数据
            mtSalesService.updateMtSales(mtSales);
        }
    }

    /**
     * 为美团销售订单加工数据：加工一条美团销售订单主表数据
     * @param mtSales   美团门店销售订单主表数据
     */
    private boolean salesProcessForWhinOrder(MtSales mtSales, MtShop mtShop) {
        //从美团接口拿到的数据没有门店Id
        mtSales.setMtShopid(mtShop.getId());

        //首先获取组织信息
        Organization organization = meituanDataProcessUtil.getOrgnization(mtShop);
        mtSales.setOrgId(organization.getId());
        mtSales.setOrgName(organization.getName());

        ProcessWrapper<Department> dprocessWrapper = meituanDataProcessUtil.getDepartment(mtShop);
        if(!dprocessWrapper.isSuccess()){
            mtSales.setStatus(10);
            mtSales.setRemark(dprocessWrapper.getMessage());
            return false;
        }
        mtSales.setDeptId(dprocessWrapper.getTarget().getId());
        mtSales.setDeptName(dprocessWrapper.getTarget().getName());

        //美团门店的销售单，需对应为ERP的菜品销售出库
        //由于美团菜品并不记录库存、也没有出入库，所以ERP系统需特定库间对应菜品的出入库
        //获取当前组织下设的库房，mtcode不为空的，第一条数据，对应的产品库
        Storeroom srlookup = new Storeroom();
        srlookup.setOrgguid(organization.getGuid());
        List<Storeroom> storeroomList = storeroomService.selectStoreroomList(srlookup);
        if(storeroomList.size()==0){
            mtSales.setStatus(10);
            mtSales.setRemark("该门店所属组织："+organization.getName()+"没有设置库房！");
            return false;
        }

        Storehouseroom storehouseroom = null;
        Storeroom storeroom = null;
        for(Storeroom sr:storeroomList){
            Storehouseroom shrLookup = new Storehouseroom();
            shrLookup.setStoreguid(sr.getGuid());
            shrLookup.setShrtype(mtFoodERPShrType);  //产成品库
            List<Storehouseroom> storehouseroomList = storehouseroomService.selectStorehouseroomList(shrLookup);
            for(Storehouseroom shr:storehouseroomList){
                if(StringUtils.isNotBlank(shr.getMtWhCode())){
                    storeroom = sr;
                    storehouseroom = shr;
                    break;
                }
            }
        }
        if(storeroom==null || storehouseroom==null){
            mtSales.setStatus(10);
            mtSales.setRemark("该门店所属组织："+organization.getName()+"没有设置产品库间！");
            return false;
        }

        mtSales.setStoreroomguid(storeroom.getGuid());
        mtSales.setStoreroomname(storeroom.getName());
        mtSales.setStorehouseguid(storehouseroom.getGuid());
        mtSales.setStorehousename(storehouseroom.getName());

        //找美团菜品对应的ERP物料
        //暂定：美团菜品的skuid设置到ERP物料的mtCode字段中
        ProcessWrapper<Salesspecification> spProcessWrapper = meituanDataProcessUtil.processSalesSpec(mtSales.getSkuid().toString(),mtShop);
        if(!spProcessWrapper.isSuccess()){
            mtSales.setRemark(spProcessWrapper.getMessage());
            mtSales.setStatus(10);
            return false;
        }

        Salesspecification salesspecification = spProcessWrapper.getTarget();
        mtSales.setProductguid(salesspecification.getProductguid());
        mtSales.setProductname(salesspecification.getProductname());
        mtSales.setSpguid(salesspecification.getGuid());
        mtSales.setSpname(salesspecification.getName());

        //库存单位
        ProcessWrapper<Stockunit> stockunitProcessWrapper = meituanDataProcessUtil.processStockUnit(salesspecification.getStockunitid());
        if(!stockunitProcessWrapper.isSuccess()){
            mtSales.setRemark(stockunitProcessWrapper.getMessage());
            mtSales.setStatus(10);
            return false;
        }

        Stockunit stockunit = stockunitProcessWrapper.getTarget();
        mtSales.setStockunitid(stockunit.getId());
        mtSales.setStockunitname(stockunit.getUnitName());

        //客户信息
        mtSales.setCustomerid(mtShop.getCustomerId());
        mtSales.setCustomername(mtShop.getCustomerName());

        //处理数量及单价
        BigDecimal rate = salesspecification.getMttostockUnitRate();
        if(rate==null || rate.compareTo(BigDecimal.ZERO)==0){
            mtSales.setRemark("物料的美团单位转换率设置错误！");
            mtSales.setStatus(10);
            return false;
        }
        mtSales.setErpWeight(new BigDecimal(mtSales.getDishsalecnt()).multiply(rate));
        mtSales.setErpPrice(mtSales.getDishincomeamt().divide(new BigDecimal(mtSales.getDishsalecnt()),6, RoundingMode.HALF_UP)
                .divide(rate,6,RoundingMode.HALF_UP));


        //开始处理明细表数据
        if(salesprocessForItems(mtSales,mtShop,storeroom,storehouseroom)){
            mtSales.setStatus(50);
            return true;
        }else{
            //明细表处理的过程中，主表状态其实已经处理过了，最终兜底
            mtSales.setStatus(10);
            return false;
        }

    }

    /**
     * 加工美团门店销售表的明细数据，加工生成门店菜品销售统计表的明细数据
     * @param mtSales   门店销售主表数据
     * @param mtShop    店铺
     * @param storeroom
     * @param storehouseroom
     */
    private boolean salesprocessForItems(MtSales mtSales, MtShop mtShop, Storeroom storeroom, Storehouseroom storehouseroom) {
        //当天该店铺的菜品消耗明细表以完成处理，成本卡已经加工完成
        MtFoodconsum mtFoodconsum = new MtFoodconsum();
        mtFoodconsum.setMtShopld(mtShop.getId());
        mtFoodconsum.setBiztime(mtSales.getBiztime());
        List<MtFoodconsum> mtFoodconsumList = mtFoodconsumService.selectMtFoodconsumList(mtFoodconsum);
        if(mtFoodconsumList.size()!=1){
            mtSales.setRemark("当前日期的美团菜品消耗表尚未处理完成！");
            mtSales.setStatus(10);
            return false;
        }
        mtFoodconsum = mtFoodconsumList.get(0);
        if(mtFoodconsum.getStatus()!=100){
            mtSales.setRemark("当前日期的美团菜品消耗表尚未处理完成！");
            mtSales.setStatus(10);
            return false;
        }

        //先删除已经存在的明细数据
        mtSalesItemsService.deleteMtSalesItemsBySaleId(mtSales.getId());

        //找到美团物品对应的ERP库房、库间
        boolean found = true;
        if(mtFoodERPShrType != mtGoodsERPShrType){
            Storehouseroom shrLookup = new Storehouseroom();
            shrLookup.setStoreguid(storeroom.getGuid());
            shrLookup.setShrtype(mtGoodsERPShrType);  //产成品库
            List<Storehouseroom> storehouseroomList = storehouseroomService.selectStorehouseroomList(shrLookup);
            found=false;
            for(Storehouseroom shr:storehouseroomList){
                if(StringUtils.isNotBlank(shr.getMtWhCode())){
                    storehouseroom = shr;
                    found=true;
                    break;
                }
            }
        }
        if(!found){
            mtSales.setRemark("当前店铺没有设置ERP原料库间！");
            mtSales.setStatus(10);
            return false;
        }
        //获取当前菜品的成本卡
        MtFoodcostcard lookup = new MtFoodcostcard();
        lookup.setMtShopId(mtShop.getId());
//        lookup.setFoodskuid(mtSales.getSkuid());
        lookup.setFoodname(mtSales.getDishname());
        lookup.setMaxEffectiveDate(new Date(mtSales.getBiztime()));

        List<MtFoodcostcard> mtFoodcostcardList = mtFoodcostcardService.selectMtFoodcostcardList(lookup);
        if(mtFoodcostcardList.size()==0){
            mtSales.setRemark("没有找到当前菜品的成本卡数据！");
            mtSales.setStatus(10);
            return false;
        }

        //第一条数据就是当前生效的成本卡数据
        MtFoodcostcard mtFoodcostcard = mtFoodcostcardList.get(0);
        //找到该条成本卡数据的明细数据
        MtFoodcostcarditem itemLookup = new MtFoodcostcarditem();
        itemLookup.setMtFoodcostcardid(mtFoodcostcard.getId());

        List<MtFoodcostcarditem> mtFoodcostcarditemList = mtFoodcostcarditemService.selectMtFoodcostcarditemList(itemLookup);

        for(MtFoodcostcarditem costcardItem:mtFoodcostcarditemList){
            MtSalesItems mtSalesItem = new MtSalesItems();
            mtSalesItem.setMtSalesid(mtSales.getId());

            mtSalesItem.setFoodskuid(mtSales.getSkuid());
            mtSalesItem.setFoodname(mtSales.getDishname());
            mtSalesItem.setFoodspec(mtSales.getDishspec());

            mtSalesItem.setBaseunitId(costcardItem.getBaseunitId());
            mtSalesItem.setBaseunitName(costcardItem.getBaseunitName());

            mtSalesItem.setMtGoodsCode(costcardItem.getMtGoodsCode());
            mtSalesItem.setMtGoodsName(costcardItem.getMtGoodsName());

            mtSalesItem.setStoreroomguid(storeroom.getGuid());
            mtSalesItem.setStoreroomname(storeroom.getName());
            mtSalesItem.setStorehouseguid(storehouseroom.getGuid());
            mtSalesItem.setStorehousename(storehouseroom.getName());

            //处理物料信息
            ProcessWrapper<Salesspecification> spProcessWrapper = meituanDataProcessUtil.processSalesSpec(costcardItem.getMtGoodsCode(),mtShop);
            if(!spProcessWrapper.isSuccess()){
                mtSales.setRemark(spProcessWrapper.getMessage());
                mtSales.setStatus(10);
                return false;
            }
            Salesspecification salesspecification = spProcessWrapper.getTarget();
            mtSalesItem.setProductguid(salesspecification.getProductguid());
            mtSalesItem.setProductname(salesspecification.getProductname());
            mtSalesItem.setSpguid(salesspecification.getGuid());
            mtSalesItem.setSpname(salesspecification.getName());

            //库存单位
            ProcessWrapper<Stockunit> stockunitProcessWrapper = meituanDataProcessUtil.processStockUnit(salesspecification.getStockunitid());
            if(!stockunitProcessWrapper.isSuccess()){
                mtSales.setRemark(stockunitProcessWrapper.getMessage());
                mtSales.setStatus(10);
                return false;
            }
            Stockunit stockunit = stockunitProcessWrapper.getTarget();
            mtSalesItem.setStockunitid(stockunit.getId());
            mtSalesItem.setStockunitname(stockunit.getUnitName());

            //数量，其实不需要处理单价的
            mtSalesItem.setAmount(new BigDecimal(mtSales.getDishsalecnt()).multiply(costcardItem.getAmount()));
            mtSalesItem.setErpWeight(mtSalesItem.getAmount().multiply(salesspecification.getMttostockUnitRate()));

            mtSalesItem.setCreateBy("1");
            mtSalesItem.setCreateTime(DateUtils.getNowDate());
            //插入当前数据
            mtSalesItemsService.insertMtSalesItems(mtSalesItem);
        }
        return true;
    }



}
